package com.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

/**
 * 监听服务端连接
 *
 * @author hcf
 * @email hcf0108@163.com
 * @create 2019-03-08 上午 10:16
 **/
public class AioServer {
    public static final int LISTEN_PORT = 7080;

    public AioServer( int port ) throws IOException {
        final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
        listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() {

            /** 异步IO完成后做的事情
             * @param ch
             * @param vi
             */
            public void completed(AsynchronousSocketChannel ch, Void vi) {
                //接受下一个连接
                listener.accept(null,this);

            }

            /** 异步IO失败后做的事情
              * @param exc
             * @param vi
             */
            public void failed(Throwable exc, Void vi) {
                System.out.println("异步IO失败");
            }
        });
    }

    /** 真正逻辑
     * @param ch
     */
    public void handler(AsynchronousSocketChannel ch) {
        try {
            ByteBuffer  bytebuffer = ByteBuffer.allocate(32);

            ch.read(bytebuffer).get();

            bytebuffer.flip();
            System.out.println("服务端接受:"+bytebuffer.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        AioServer aioServer = new AioServer(LISTEN_PORT);
        System.out.println("监听端口为："+LISTEN_PORT);
        Thread.sleep(10);


    }
}
